package com.dhcc.bpm.modules.content.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dhcc.bpm.common.annotation.Log;
import com.dhcc.bpm.common.enums.BusinessType;
import com.dhcc.bpm.modules.content.dto.FaqDTO;
import com.dhcc.bpm.modules.content.entity.Faq;
import com.dhcc.bpm.modules.content.service.IFaqService;
import com.dhcc.bpm.modules.content.vo.FaqVO;
import com.dhcc.bpm.modules.system.entity.Dict;
import com.dhcc.bpm.modules.system.service.IDictService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

import javax.validation.Valid;
import java.security.SecureRandom;
import java.util.*;

/**
 * @ClassName FaqController
 * @Description FAQ管理 控制器
 * @Author lijiacheng
 * @Date 2020/2/21 14:16
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 */

@RestController
@AllArgsConstructor
@RequestMapping("bpm-content/faq")
@Api(value = "", tags = "接口")
public class FaqController extends BladeController {

    private IFaqService faqService;

    private IDictService dictService;

    /**
     * 详情
     */
    @ApiLog("FAQ模块表详情")
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入faq")
    public R<Faq> detail(Faq faq) {
        Faq detail = faqService.getOne(Condition.getQueryWrapper(faq));
        return R.data(detail);
    }

    /**
     * 分页
     */
    @ApiLog("FAQ模块表列表")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productName", value = "产品名称", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "apiName", value = "api名称", paramType = "query", dataType = "string")
    })
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入faq")
    public R<IPage<Faq>> list(@ApiIgnore @RequestParam Map<String, Object> faq, Query query) {
        IPage<Faq> pages = faqService.page(Condition.getPage(query), Condition.getQueryWrapper(faq, Faq.class));
        return R.data(pages);
    }

    /**
     * 分页
     */
    @ApiLog("FAQ模块表树")
    @GetMapping("/listTree")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productName", value = "产品名称", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "apiName", value = "api名称", paramType = "query", dataType = "string")
    })
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "树形排列分页", notes = "传入faq")
    public R<List<FaqDTO>> listTree(FaqVO faq, Query query) {
//		List<Faq> faqList = faqService.list(Condition.getQueryWrapper(faq, Faq.class));
        List<FaqVO> faqList = faqService.listSelf(faq);
        List<String> productList = new ArrayList<>();
        faqList.forEach(faq1 -> {
            productList.add(faq1.getProductName());
        });
        Set set = new HashSet();
        List<FaqDTO> faqDtoList = new LinkedList<>();
        productList.forEach(product -> {
            if (set.add(product)) {
                FaqDTO faqDTO = new FaqDTO();
//				QueryWrapper<Faq> queryWrapper = new QueryWrapper<>();
                FaqVO faqVO = new FaqVO();
                BeanUtils.copyProperties(faq, faqVO);
                faqVO.setProductName(product);
//				List<FaqVO> list = faqService.list((queryWrapper.lambda().eq(Faq::getProductName,product)));
                List<FaqVO> list = faqService.listSelf(faqVO);
                faqDTO.setChildren(list);
                String val = "";
                Random random = new SecureRandom();
                ;
                for (int i = 0; i < 10; i++) {
                    val += String.valueOf(random.nextInt(10));
                }
                faqDTO.setId(Long.valueOf(val));
                faqDTO.setProductName(product);
                faqDTO.setStatus(9);
                faqDtoList.add(faqDTO);
            }
        });
//		Integer current = query.getCurrent();
//		Integer pageSize = query.getSize();
//		List<FaqDTO> listSort = new ArrayList<>();
//		Integer size = faqDTOList.size();
//		Integer pageStart = current==1?0:(current-1)*pageSize;
//		Integer pageEnd = size<current*pageSize?size:current*pageSize;
//		if(size > pageStart){
//			listSort.addAll(faqDTOList.subList(pageStart, pageEnd));
//		}
//		FaqPage faqPage = new FaqPage();
//		faqPage.setRecords(listSort);
//		faqPage.setCurrent(current);
//		faqPage.setSize(size);
//		faqPage.setTotal(listSort.size());
        return R.data(faqDtoList);
    }

    /**
     * 自定义分页
     */
    @ApiLog("FAQ模块表分页")
    @GetMapping("/page")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "分页", notes = "传入faq")
    public R<IPage<FaqVO>> page(FaqVO faq, Query query) {
        IPage<FaqVO> pages = faqService.selectFaqPage(Condition.getPage(query), faq);
        return R.data(pages);
    }

    /**
     * 新增
     */
    @ApiLog("FAQ模块表新增")
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入faq")
    @Log(title = "新增FAQ", businessType = BusinessType.INSERT)
    public R save(@Valid @RequestBody Faq faq) {
        return R.status(faqService.save(faq));
    }

    /**
     * 修改
     */
    @ApiLog("FAQ模块表更新")
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改", notes = "传入faq")
    @Log(title = "修改FAQ", businessType = BusinessType.UPDATE)
    public R update(@Valid @RequestBody Faq faq) {
        return R.status(faqService.updateById(faq));
    }

    /**
     * 新增或修改
     */
    @ApiLog("FAQ模块表提交")
    @PostMapping("/submit")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "新增或修改", notes = "传入faq")
    @Log(title = "FAQ管理", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    public R submit(@Valid @RequestBody Faq faq) {
        String tag = faq.getTag();
        List<Dict> tree = dictService.getList("faq_tag");
        boolean flag = true;
        for (Dict dict : tree) {
            if (dict.getDictKey().equals(tag)) {
                flag = false;
            }
        }
        if (flag) {
            Dict dict = new Dict();
            dict.setParentId(1225609744208924673L);
            dict.setCode("faq_tag");
            dict.setDictKey(tag);
            dict.setDictValue(tag);
            dict.setSort(1);
            dict.setIsSealed(0);
            dict.setIsDeleted(0);
            dictService.submit(dict);
        }
        if (faq.getId() == null) {
//			LambdaQueryWrapper<Faq> wrapper = new LambdaQueryWrapper();
//			wrapper.eq(Faq::getQuestion,faq.getQuestion()).eq(Faq::getAnswer,faq.getAnswer()).eq(Faq::getProductName,faq.getProductName())
//					.eq(Faq::getApiName,faq.getApiName()).eq(Faq::getTag,faq.getTag());
//			List<Faq> list = faqService.list(wrapper);
            List<Faq> list = faqService.list(faq);
            if (list != null && list.size() >= 1) {
                return R.fail("该问题已存在");
            }
        }
        return R.status(faqService.saveOrUpdate(faq));
    }


    /**
     * 删除
     */
    @ApiLog("FAQ模块表删除")
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "逻辑删除", notes = "传入ids")
    @Log(title = "FAQ删除", businessType = BusinessType.DELETE)
    public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        return R.status(faqService.deleteLogic(Func.toLongList(ids)));
    }

    /**
     * 详情
     */
    @ApiLog("FAQ模块表删除TAG")
    @GetMapping("/faqTagDel")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "删除标签", notes = "传入tag")
    public R faqTagDel(String tag) {
        List<Dict> tree = dictService.getList("faq_tag");
        for (Dict dict : tree) {
            if (dict.getDictValue().equals(tag)) {
                dictService.removeDict(String.valueOf(dict.getId()));
            }
        }
        return R.data(true);
    }


}
